package cn.fch.gotrip.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @program: gotrip
 * @description:
 * @CreatedBy: fch
 * @create: 2023-01-17 17:17
 **/
@Component
public class UploadUtil {
    public String uploadImg(String childPath, String imgName, MultipartFile file, HttpServletRequest request) throws IOException {
        String path = request.getServletContext().getRealPath(childPath);
        //创建文件夹，但凡你要操作文件或者文件夹，你都要先创建它对应的File对象
        File desDir = new File(path);
        if (!desDir.exists()) {
            //mkdirs()和mkdir()区别
            desDir.mkdirs();
        }
        //2.上传文件
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String desFileName = imgName + suffix;
        //但凡你要操作文件或者文件夹，你都要先创建它对应的File对象
        File desFile = new File(path, desFileName);
        file.transferTo(desFile);
        return childPath + desFileName;
    }
}
